<template>
  <div>
    <van-cell
    v-for="(item,index) in suggestions"
    :key="index"
    icon="search"
    @click="$emit('search',item)"
    >
    <div slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
// import { debounce } from 'lodash'
function debounce (fn, wait) {
  let timer = null
  return function (val) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.call(this, val)
    }, wait)
  }
}
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  components: {},
  data () {
    return {
      suggestions: [],
      timer: null
    }
  },
  created () {},
  mounted () {},
  methods: {
    highlight (text) {
      if (text) {
        return text.replace(new RegExp(this.searchText, 'gi'), `<span style="color:red">${this.searchText}</span>`)
      } else {
        return text
      }
    }
  },
  watch: {
    // 在对象当中定义方法
    // searchText: function () {}
    // searchText: () => {}
    // 侦听器基本写法
    // searchText (val) {
    //   console.log(val)
    // }
    searchText: {
      // 方式一:手写节流
    //   handler (val) {
    //     if (this.timer) clearTimeout(this.timer)
    //     this.timer = setTimeout(async () => {
    //       const { data: { data: { options } } } = await getSearchSuggestions(val)
    //       this.suggestions = options
    //     }, 500)
    //   },
    //   immediate: true // 打开立即执行
    // }
      handler: debounce(async function (val) {
        const { data: { data: { options } } } = await getSearchSuggestions(val)
        this.suggestions = options
      }, 500),
      immediate: true // 打开立即执行
    }
  },
  computed: {}
}
</script>

<style lang="less" scoped>
</style>
